package great.easychat.help.dialog;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.pince.logger.LogUtil;
import com.qizhou.base.dialog.lifecycledialog.BaseDialogFragment;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;

import great.easychat.help.CustomAppcation;
import great.easychat.help.R;
import great.easychat.help.dialog.gravity.GravityEnum;
import great.easychat.help.util.ToastUtil;

import static great.easychat.help.update.FileConstants.CACHE_IMAGE_DIR;
import static great.easychat.help.update.FileConstants.CACHE_PATH;

/**
 * Create time 2020/3/26
 * 花田分享弹窗
 */
public class ShareDialogFragment extends BaseDialogFragment implements View.OnClickListener {

    LinearLayout llCover, llWeChat, llFriend;
    ImageView ivQrCode;
    ImageView ivAvatar;
    TextView tvName, tvId;
    RelativeLayout rlRoot;

    public ShareDialogFragment() {
        applyCancelable(true);
        applyGravityStyle(GravityEnum.HeightFullScreen);
    }

    @Override
    public int getViewLayoutId() {
        return R.layout.dialog_share;
    }

    @Override
    public void init() {
        View view = getView();
        llCover = view.findViewById(R.id.llCover);
        llWeChat = view.findViewById(R.id.llWeChat);
        llFriend = view.findViewById(R.id.llFriend);
        ivQrCode = view.findViewById(R.id.ivQrCode);
        tvName = view.findViewById(R.id.tvName);
        tvId = view.findViewById(R.id.tvId);
        ivAvatar = view.findViewById(R.id.ivAvatar);
        rlRoot = view.findViewById(R.id.rlRoot);
        llWeChat.setOnClickListener(this);
        llFriend.setOnClickListener(this);
        rlRoot.setOnClickListener(this);
        String shareUrl = "http://app_download.chattinghelper.cn/download?uideex=43r4ffw";
        LogUtil.d("shareUrl--->" + shareUrl);
        Bitmap bitmap = createQRCodeBitmap(shareUrl, 400, 400, "UTF-8", "H", "1", Color.BLACK, Color.WHITE);
        ivQrCode.setImageBitmap(bitmap);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }


    private Bitmap getCover() {
        llCover.setDrawingCacheEnabled(true);
        llCover.buildDrawingCache();
        Bitmap bmp = llCover.getDrawingCache(); // 获取图片
        Bitmap bmp2 = Bitmap.createBitmap(bmp);
        llCover.destroyDrawingCache();
        llCover.setDrawingCacheEnabled(false);// 以清空画图缓冲区，否则下一次还是原来的图像
        return bmp2;
    }

    String pathShare = CACHE_PATH + "share.jpg";
    private void saveBitmap(Bitmap bitmap) {
        File file = new File(pathShare);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        // https://developer.umeng.com/docs/128606/detail/129622#h3--
        if (v == llWeChat) {
            saveBitmap(getCover());
            shareWeChat();
        } else if (v == llFriend) {
            saveBitmap(getCover());
        } else if (v == rlRoot) {
            dismiss();
        }
    }


    // 把图片分享给微信好友
    private void shareWeChat() {
        Uri uriToImage = Uri.fromFile(new File(pathShare));
        Intent shareIntent = new Intent();
        //发送图片给好友。朋友圈 com.tencent.mm.ui.tools.ShareToTimeLineUI
        ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
        shareIntent.setComponent(comp);
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        shareIntent.setType("image/*");
        shareIntent.putExtra("Kdescription", ""); //微信分享页面，图片上边的描述

        getActivity().startActivity(shareIntent);
    }

    // 把文字分享给微信好友
    public void shareWechatFriend(Context context, String content) {
        if (CustomAppcation.isWeChatAppInstalled()) {
            Intent intent = new Intent();
            ComponentName cop = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
            intent.setComponent(cop);
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra("android.intent.extra.TEXT", content);
            intent.putExtra("Kdescription", !TextUtils.isEmpty(content) ? content : "");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            ToastUtil.show("您需要安装微信客户端");
        }
    }

    /**
     * 生成简单二维码
     *
     * @param content                字符串内容
     * @param width                  二维码宽度
     * @param height                 二维码高度
     * @param character_set          编码方式（一般使用UTF-8）
     * @param error_correction_level 容错率 L：7% M：15% Q：25% H：35%
     * @param margin                 空白边距（二维码与边框的空白区域）
     * @param color_black            黑色色块
     * @param color_white            白色色块
     * @return BitMap
     */
    public static Bitmap createQRCodeBitmap(String content, int width, int height,
                                            String character_set, String error_correction_level,
                                            String margin, int color_black, int color_white) {
        // 字符串内容判空
        if (TextUtils.isEmpty(content)) {
            return null;
        }
        // 宽和高>=0
        if (width < 0 || height < 0) {
            return null;
        }
        try {
            /** 1.设置二维码相关配置 */
            Hashtable<EncodeHintType, String> hints = new Hashtable<>();
            // 字符转码格式设置
            if (!TextUtils.isEmpty(character_set)) {
                hints.put(EncodeHintType.CHARACTER_SET, character_set);
            }
            // 容错率设置
            if (!TextUtils.isEmpty(error_correction_level)) {
                hints.put(EncodeHintType.ERROR_CORRECTION, error_correction_level);
            }
            // 空白边距设置
            if (!TextUtils.isEmpty(margin)) {
                hints.put(EncodeHintType.MARGIN, margin);
            }
            /** 2.将配置参数传入到QRCodeWriter的encode方法生成BitMatrix(位矩阵)对象 */
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            /** 3.创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    //bitMatrix.get(x,y)方法返回true是黑色色块，false是白色色块
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = color_black;//黑色色块像素设置
                    } else {
                        pixels[y * width + x] = color_white;// 白色色块像素设置
                    }
                }
            }
            /** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象 */
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }


}
